// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Game from "./Game";
import Score from "./Score";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Target extends cc.Component {

    @property(cc.AudioClip)
    audio: cc.AudioClip = null;

    speed: number = 200;

    private canvas: cc.Node = null;
    private label: cc.Label = null;
    private scoreValue: number = 0;
    private healthPoint: number = 0;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

    }

    // 由于Target节点时重复使用的，所以重新使用之前重置一下
    onEnable() {
        
        this.canvas = cc.find('Canvas');
        this.label = this.node.children[0].getComponent(cc.Label);

        this.scoreValue = 1 + Math.floor(Math.random() * 10);
        this.healthPoint = this.scoreValue;
        this.showHealth();
    }

    start () {

    }

    showHealth() {

        this.label.string = this.healthPoint + '';
    }

    dismiss() {

        Game.inst.destroyTarget(this.node);
    }

    update (dt) {

        let step = this.speed * dt;
        this.node.y -= step;

        if(this.node.y < - this.canvas.height/2 - this.node.height) {

            this.dismiss();

            cc.log('Target超出视野, 自动销毁');
        }
    }

    onCollisionEnter(other: cc.Collider, self: cc.Collider) {

        if(other.node.name == '玩家子弹') {

            this.healthPoint -= 1;
            this.showHealth();
    
            self.node.scale = 1;

            // 0.5s内放大到1.2, 0.2s内变回1
            cc.tween(self.node)
              .to(0.2, {scale : 1.2}, {easing: 'cubicOut'})
              .to(0.2, {scale : 1}, {easing: 'cubicOut'})
              .start();

            //cc.log("击中");

            if(this.healthPoint <= 0) {
    
                Score.i.addScore(this.scoreValue);

                this.dismiss();

                cc.audioEngine.play(this.audio, false, 1);
            }
        }

    }
}
